﻿namespace BM.Tools.WebControls.MForm.Controls.Helper.EventValidation
{    
    using System;
    using System.Collections.Generic;
    using System.Web.UI;

    using Items;

    /// <summary>
    /// A class for seaching event handler inner controls.
    /// </summary>
    internal static class EventHandlersSearch
    {
        private static Dictionary<Type, bool> typesSupportsEventValidation = new Dictionary<Type, bool>();

        /// <summary>
        /// Recursively searches for controls that support event validation (unless it finds an OffspringItem).
        /// </summary>
        /// <param name="control">
        /// The control.
        /// </param>
        /// <returns>
        /// All inner event handlers.
        /// </returns>
        public static IEnumerable<Control> GetEventHandlers(this Control control)
        {
            foreach (Control c in control.Controls)
            {
                var childItem = c as OffspringItem;
                if (childItem != null)
                {
                    continue;
                }

                if (SupportsEventValidation(c.GetType()))
                {
                    yield return c;
                }

                foreach (var child in GetEventHandlers(c))
                {
                    yield return child;
                }
            }
        }

        private static bool SupportsEventValidation(Type type)
        {
            if (typesSupportsEventValidation.ContainsKey(type))
            {
                return typesSupportsEventValidation[type];
            }

            object[] customAttributes = type.GetCustomAttributes(typeof(SupportsEventValidationAttribute), false);
            var attributeExists = (customAttributes != null) && (customAttributes.Length > 0);
            typesSupportsEventValidation[type] = attributeExists;
            return attributeExists;
        }
    }
}
